<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="电影名" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.genre" placeholder="电影类型" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key"/>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="编号" prop="id" sortable="custom" :class-name="getSortClass('id')"
                       align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电影" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="电影类型" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.genre }}</span>
        </template>
      </el-table-column>
      <el-table-column label="导演" width="300px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.crew }}</span>
        </template>
      </el-table-column>
      <el-table-column label="主演" width="400px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cast }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.runtime }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable="custom" :class-name="getSortClass('start_date')"
                       prop="startDate" label="上映时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startDate | formatDate }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination style="text-align:center" v-show="total>0" :total="total" :page.sync="listQuery.page"
                :limit.sync="listQuery.limit" @pagination="getList"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp"
               label-position="right" label-width="100px"
               style="width: 500px; margin-left:50px;">
        <el-form-item label="电影名" prop="name">
          <el-input v-model="temp.name"/>
        </el-form-item>
        <el-form-item label="电影类型" prop="genre">
          <el-input v-model="temp.genre"/>
        </el-form-item>
        <el-form-item label="导演" prop="crew">
          <el-input v-model="temp.crew"/>
        </el-form-item>
        <el-form-item label="主演" prop="cast">
          <el-input v-model="temp.cast"/>
        </el-form-item>
        <el-form-item label="时长" prop="runtime">
          <el-input v-model="temp.runtime"/>
        </el-form-item>
        <el-form-item label="上映日期" prop="startDate">
          <el-date-picker v-model="temp.startDate" type="date" placeholder="请选择一个日期"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {fetchFilms, createFilm, updateFilm, removeFilm} from '@/api/film'
  import {parseTime} from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  export default {
    name: 'ComplexTable',
    components: {Pagination},
    filters: {
      formatDate(str) {
        return str.substring(0, 10)
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,  // 数据加载状态
        listQuery: { // 查询条件
          page: 1,
          limit: 10,
          name: undefined,
          genre: undefined,
          sort: '+start_date'
        },
        sortOptions: [{label: '上映时间升序', key: '+start_date'},
          {label: '上映时间降序', key: '-start_date'}],
        temp: {
          id: undefined,
          name: undefined,
          genre: undefined,
          crew: undefined,
          cast: undefined,
          runtime: undefined,
          startDate: undefined
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新建'
        },
        rules: {
          name: [{required: true, message: '请填写电影名', trigger: 'change'}],
          genre: [{required: true, message: '请填写电影类型', trigger: 'change'}],
          cast: [{required: true, message: '请填写导演', trigger: 'change'}],
          crew: [{required: true, message: '请填写主演', trigger: 'change'}],
          runtime: [{required: true, message: '请填写时长', trigger: 'change'}],
          startDate: [{type: 'date', required: true, message: '请选择上映日期', trigger: 'change'}],
        }
      }
    },
    created() {
      this.getList()
    },

    methods: {
      async getList() { // 按条件查询分页数据
        this.listLoading = true
        let response = await fetchFilms(this.listQuery)
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      },
      handleFilter() { // 从第一页重新查询；每次点击查询、修改排序方式、或在查询条件中按回车时调用
        this.listQuery.page = 1
        this.getList()
      },
      sortChange(data) { // 点击表头排序按钮时调用
        const {prop, order} = data
        console.log(data)
        if (prop === 'startDate') {
          this.sortByStartDate(order)
        } else if (prop === 'id') {
          this.sortById(order)
        }
      },
      sortById(order) { // 按照 id 进行排序
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      sortByStartDate(order) { // 按照上映日期进行排序
        if (order === 'ascending') {
          this.listQuery.sort = '+start_date'
        } else {
          this.listQuery.sort = '-start_date'
        }
        this.handleFilter()
      },
      resetTemp() { // 重置 编辑/新建 页面绑定的数据
        this.temp = {
          id: undefined,
          name: undefined,
          genre: undefined,
          crew: undefined,
          cast: undefined,
          runtime: undefined,
          startDate: undefined
        }
      },
      handleCreate() {  // 进入创建电影记录页面
        this.resetTemp()  // 重置新记录的数据
        this.dialogStatus = 'create'  // 将对话框设置为创建状态
        this.dialogFormVisible = true //  显示对话框
        this.$nextTick(() => { // 在下一个时钟周期清理验证信息
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() { // 新增数据
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {  // 验证成功
            console.log(this.temp)
            // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.id = null
            createFilm(this.temp).then(response => { // 发起创建电影请求
              console.log('新建：')
              console.log(response)
              this.list.unshift(response.data)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) { // 打开编辑页面
        this.temp = Object.assign({}, row) // copy obj
        this.temp.startDate = new Date(this.temp.startDate) // 将页面上日期字符串转换为日期对象
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() { // 更新数据
        this.$refs['dataForm'].validate((valid) => {
          if (valid) { // 验证成功
            // 将表单中 电影 数据复制到 tempData
            const tempData = Object.assign({}, this.temp)
            // 将日期转换为 毫秒值
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateFilm(tempData).then(() => {
              // 在电影列表中找到 id === tempData.id 的电影索引
              const index = this.list.findIndex(v => v.id === this.temp.id)
              this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row, index) { // 删除记录
        this.$confirm('此操作将永久删除该电影, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await removeFilm(row)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      // 暂时无用
      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      // 更新表格头部的排序样式；本例是上映时间
      getSortClass: function (key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
